package org.example.lostandfound.controller;


import org.example.lostandfound.model.User;
import org.example.lostandfound.service.UserService;
import org.example.lostandfound.util.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
@RequestMapping("/api/users")

public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAllUsers();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.findUserById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        }else{
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public void registerUser(@RequestBody User user) {
        userService.registerUser(user);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        User updatedUser = userService.updateUser(user);
        if (updatedUser != null) {
            return ResponseEntity.ok(updatedUser);
        }else{
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<User> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }


    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user, HttpSession session) {
        String verificationCode = VerificationCodeUtil.generateVerificationCode(6);//生成6位验证码
        session.setAttribute("verificationCode", verificationCode);//存贮验证码到会话中
        User loggedInUser = userService.loginUser(user.getPhoneNumber(), user.getPassword());
        if (loggedInUser != null) {
            //将用户信息存储到Session中
            session.setAttribute("user", loggedInUser);
            return ResponseEntity.ok().body(loggedInUser);
        }else{
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid name or password or verification code");
        }
    }


}
